/**
 * UB-RIA-UI 1.0
 *
 * @ignore
 * @file 地址控件
 * @author maoquan
 */

define(
    function (require) {
        var TextBox = require('esui/TextBox');
        var esui = require('esui');
        var lib = require('esui/lib');
        var eoo = require('eoo');
        var painters = require('esui/painters');
        var u = require('underscore');
        var $ = require('jquery');
        var loadScript = require('./loadScript');

        require('ub-ria-ui/AutoComplete');

        var AMAP_URL = 'http://webapi.amap.com/maps?v=1.3&key=d766ab59d9d45c1031756f81cbdaf02f';

        var TPL = '${address}'; //'[经度: ${lng}, 纬度: ${lat}]';

        /**
         * 地址控件
         *
         * @class ui.Address
         * @extends.esui.TextBox
         */
        var Address = eoo.create(
            TextBox,
            {
                /**
                 * 控件类型，始终为`"Address"`
                 *
                 * @type {string}
                 * @override
                 */
                type: 'Address',

                styleType: 'textbox',

                initOptions: function (options) {
                    var properties = {
                        minSearchLength: 2,
                        addressValue: {}
                    };
                    u.extend(properties, options);

                    this.$super([properties]);
                },

                initStructure: function () {
                    this.$super(arguments);
                    var input = lib.g(this.inputId);
                    lib.setAttribute(input, 'autocomplete', 'off');
                },

                initEvents: function () {
                    this.$super(arguments);
                    this.on(
                        'targetselect',
                        function (e) {
                            if (u.isString(e.id)) {
                                var datas = e.id.split('|');
                                this.setProperties(
                                    {
                                        rawValue: {
                                            name: datas[0],
                                            longitude: datas[1],
                                            latitude: datas[2]
                                        }
                                    }
                                );
                            }
                        },
                        this
                    );
                },

                repaint: require('esui/painters').createRepaint(
                    TextBox.prototype.repaint,
                    {
                        name: ['rawValue'],
                        paint: function (me, rawValue) {
                            if (u.isObject(rawValue)) {
                                me.addressValue = rawValue;
                                var input = lib.g(me.inputId);
                                input.value = rawValue.name || '';
                            }
                        }
                    }
                ),

                getRawValue: function () {
                    return this.addressValue;
                },

                query: {city: '021'},

                datasource: function (value, callback) {
                    if (value.length < this.control.minSearchLength) {
                        return [];
                    }
                    if (!window.AMap) {
                        loadScript(AMAP_URL, u.bind(doSearch, this.control, value, callback));
                    }
                    else {
                        doSearch.call(this.control, value, callback)
                    }
                }
            }
        );

        function doSearch(value, callback) {
            var me = this;
            AMap.service(
                'AMap.PlaceSearch',
                function () {
                    var query = me.query;
                    var query = u.isFunction(query)
                        ? query.call(null) : query;
                    var placeSearch = new AMap.PlaceSearch(query);
                    //地理编码
                    placeSearch.search(
                        value,
                        function (status, result) {
                            if (status === 'complete' && result.info === 'OK') {
                                var codes = [];
                                var poiList = result.poiList;
                                var hasAddress = u.some(poiList.pois, function (poi) {return !!poi.address;});
                                if (poiList.count > 0 && hasAddress) {
                                    u.each(
                                        poiList.pois,
                                        function (poi) {
                                            if (poi.address) {
                                                codes.push(
                                                    {
                                                        text: lib.format(
                                                            TPL,
                                                            {
                                                                address: poi.address,
                                                                lng: poi.location.lng,
                                                                lat: poi.location.lat
                                                            }
                                                        ),
                                                        id: [poi.address, poi.location.lng, poi.location.lat].join('|')
                                                    }
                                                );
                                            }
                                        }
                                    );
                                }
                                callback(codes);
                            }
                        }
                    );
                }
            );
        }

        esui.register(Address);
        return Address;
    }
);
